#!/bin/bash
# Start/stop shadowsocks.
#
#====================================================================
# Run level information:
# chkconfig: 2345 99 99
# Description: lightweight secured socks5 proxy
# processname: shadowsocks-server
# Run "/sbin/chkconfig --add shadowsocks" to add the Run levels.
#====================================================================

# Note: this script requires sudo in order to run shadowsocks as the specified
# user. 

# Source function library
. /etc/rc.d/init.d/functions

# Check that networking is up.
[ ${NETWORKING} ="yes" ] || exit 0

BIN=/usr/bin/shadowsocks-server
CONFIG_FILE=/etc/shadowsocks/config.json
PID_DIR=/var/run
PID_FILE=$PID_DIR/shadowsocks.pid
RET_VAL=0

[ -x $BIN ] || exit 0

check_running() {
  if [[ -r $PID_FILE ]]; then
    read PID <$PID_FILE
    if [[ -d "/proc/$PID" ]]; then
      return 0
    else
      rm -f $PID_FILE
      return 1
    fi
  else
    return 2
  fi
}

do_status() {
  check_running
  case $? in
    0)
      echo "shadowsocks-go running with PID $PID"
      ;;
    1)
      echo "shadowsocks-go not running, remove PID file $PID_FILE"
      ;;
    2)
      echo "Could not find PID file $PID_FILE, shadowsocks-go does not appear to be running"
      ;;
  esac
  return 0
}

do_start() {
  if [[ ! -d $PID_DIR ]]; then
    mkdir $PID_DIR || echo "failed creating PID directory $PID_DIR"; exit 1
  fi
  if check_running; then
    echo "shadowsocks-go already running with PID $PID"
    return 0
  fi
  if [[ ! -r $CONFIG_FILE ]]; then
    echo "config file $CONFIG_FILE not found"
    return 1
  fi
  echo "starting shadowsocks-go"
  # sudo will set the group to the primary group of $USER
  $BIN -c $CONFIG_FILE > /dev/null &
  PID=$!
  echo $PID > $PID_FILE
  sleep 0.3
  if ! check_running; then
    echo "start failed"
    return 1
  fi
  echo "shadowsocks-go running with PID $PID"
  return 0
}

do_stop() {
  if check_running; then
    echo "stopping shadowsocks-go with PID $PID"
    kill $PID
    rm -f $PID_FILE
  else
    echo "Could not find PID file $PID_FILE"
  fi
}

do_restart() {
  do_stop
  do_start
}

case "$1" in
  start|stop|restart|status)
    do_$1
    ;;
  *)
    echo "Usage: shadowsocks {start|stop|restart|status}"
    RET_VAL=1
    ;;
esac

exit $RET_VAL
